const apiServer = require('../api-server')
// const Datasource = require('@config/data-source')
const PostgresqlConnect = require('./db-connect/postgresql-connect')
const connectMap = {
  'postgresql': PostgresqlConnect
}
Promise.allSettled = function(promiseResultList = []) {
  const result = []
  return new Promise((resolve, reject) => {
    function loop(list, index) {
      if (index >= list.length) {
        resolve(result)
        return
      }
      list[index].then(res => {
        result[index] = res
        index++
        loop(list, index)
      }).catch(err => {
        result[index] = err
        index++
        loop(list, index)
      })
    }
    loop(promiseResultList, 0)
  })
}
/**
 * 数据库服务
 * 以下的几个传入的配置介绍
 * Datasource 数据源配置对象
 * router 路由
 * ResultVo 可以是exmd框架的也可以自己定义
 * authDataSourceKey 登录注册授权模块需要使用到的数据源配置对应的key
 * authUserModel 登录注册对应model类，外部传入是提供自定义
 * @param {*} projectConfig 配置，使用者传入
 */
function dbServer(projectConfig) {
  const { 
    Datasource, 
    router, 
    ResultVo, 
    authDataSourceKey,
    authUserModel,
    authPrivateKey,
    authTokenTime
  } = projectConfig
  const resultList = []
  const funNameList = []
  for (let sourceName in Datasource) {
    const funName = connectMap[Datasource[sourceName].type]
    if (funName) {
      resultList.push(funName(Datasource[sourceName].data))
      funNameList.push(sourceName)
    }
  }
  Promise.allSettled(resultList).then(res => {
    const dbClient = {}
    funNameList.forEach((item, key) => {
      dbClient[item] = res[key]
      console.log(`log: 数据库[${item}连接池开启]`)
    })
    // 将连接池注入到控制器和业务层中
    apiServer({
      dbClient,
      router,
      ResultVo,
      authDataSourceKey,
      authUserModel,
      authPrivateKey,
      authTokenTime
    })
  })
}

module.exports = dbServer